#include "SqlOperator.h"

SqlOperator::SqlOperator(const QString &tableName, QObject* parent) :
    QObject(parent)
{
    m_query = QSqlQuery(globalDB);  //重新载入
    this->setSqlTable(tableName);
}

SqlOperator::~SqlOperator()
{

}

RobotBaseData SqlOperator::readSqlData(int index)
{
    m_query.seek(index);    //查询index位置的数据信息
    if ( !m_query.isActive() ) {
        qDebug() << "Query defeate due to m_query is not active";
        return m_data;
    }
    m_data.num = m_query.value(0).toInt();
    m_data.net = m_query.value(1).toInt();
    m_data.x = m_query.value(2).toDouble() * 10;
    m_data.y = m_query.value(3).toDouble() * 10;
    m_data.theta = m_query.value(4).toDouble();
    m_data.p = m_query.value(5).toDouble();
    m_data.v = m_query.value(6).toDouble();
    m_data.wv = m_query.value(7).toDouble();
    m_data.ele = m_query.value(8).toDouble();
    m_data.state = static_cast<RobotRunningState>(m_query.value(9).toInt());
    m_data.load = m_query.value(10).toDouble();

    emit dataRefresh(m_data);
    return m_data;
}

bool SqlOperator::writeData(const RobotBaseData &data)
{
    m_query.prepare("insert into " + m_tableName +
                    " (tro_num, tro_net, x_pos, y_pos, theta_pos, "
                    "p, v, wv, tro_ele, tro_sta, tro_load) "
                    "values(:num, :net, :x, :y, :theta, :p, :v, :wv, :ele, :sta, :load)");
    m_query.bindValue(":num", data.num);
    m_query.bindValue(":net", data.net);
    m_query.bindValue(":x", data.x);
    m_query.bindValue(":y", data.y);
    m_query.bindValue(":theta", data.theta);
    m_query.bindValue(":p", data.p);
    m_query.bindValue(":v", data.v);
    m_query.bindValue(":wv", data.wv);
    m_query.bindValue(":ele", data.ele);
    m_query.bindValue(":sta", static_cast<int>(data.state));
    m_query.bindValue(":load", data.load);

    if (!m_query.exec()) {
        qDebug() << "Insert error " + m_query.lastError().text();
        return false;
    }
    else
    {
        return true;
    }

    return true;
}

void SqlOperator::setSqlTable(const QString &tableName)
{
    m_tableName = tableName;
    m_query.prepare("select * from " + m_tableName);
    m_query.exec();
}
